package com.seele.tigerwallet.ui.activtiy;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.seele.tigerwallet.R;
import com.seele.tigerwallet.ui.base.TitleBaseActivity;
import com.seele.tigerwallet.ui.utils.PermissionFail;
import com.seele.tigerwallet.ui.utils.PermissionSuccess;
import com.seele.tigerwallet.ui.utils.PermissionUtil;
import com.seele.tigerwallet.ui.views.HtmlWebView;

public class CustomerActivity extends TitleBaseActivity {

    private WebView mWebView;

    private final int PER_CAMERA = 3;
    String url = "https://qiyukf.com/client?k=4b6e3f9c38e05a54546de9eeee2b157a";
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    private ValueCallback<Uri[]> mUploadMessageArray;
    private ValueCallback<Uri> mUploadMessage;


    @Override
    public int getContainerViewId() {
        return R.layout.activity_customer;
    }

    @Override
    protected void initView() {
        mWebView = findViewById(R.id.webview);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        initView(url);

    }


    public void initView(String url) {

        setTitle(R.string.contact_us);

        WebSettings s = mWebView.getSettings();
        s.setBuiltInZoomControls(true);
        s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        s.setUseWideViewPort(true);
        s.setLoadWithOverviewMode(true);
        s.setSavePassword(true);
        s.setSaveFormData(true);
        s.setJavaScriptEnabled(true);
        s.setGeolocationEnabled(true);
        s.setGeolocationDatabasePath(url);
        s.setDomStorageEnabled(true);

        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
//                dialog.cancel();

                super.onPageFinished(view, url);
            }

        });

        mWebView. loadUrl(url);

    }


    @PermissionSuccess(requestCode = PER_CAMERA)
    private void grantPermissionSuccess() {
        openAlbum();

    }

    @PermissionFail(requestCode = PER_CAMERA)
    private void grantPersmissionFail() {
        Toast.makeText(this, getResources().getString(R.string.read_external_storage), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtil.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }




    class MyWebChromeClient extends WebChromeClient {
        // For Android  >= 3.0
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            if (acceptType.equals("image/*")) {
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                    return;
                }
                mUploadMessage = uploadMsg;
                selectImage();
            } else {

            }

        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "image/*");

        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);

        }

        @SuppressLint("NewApi")
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                    && fileChooserParams.getAcceptTypes().length > 0 && fileChooserParams.getAcceptTypes()[0].equals("image/*")) {
                if (mUploadMessageArray != null) {
                    mUploadMessageArray.onReceiveValue(null);
                }
                mUploadMessageArray = filePathCallback;
                selectImage();
            } else {

            }

            return true;
        }
    }

    private void selectImage() {

        PermissionUtil.needPermission(this, PER_CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE);

    }

    private void openAlbum() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == mUploadMessage && null == mUploadMessageArray) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadMessageArray != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || mUploadMessageArray == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadMessageArray.onReceiveValue(results);
        mUploadMessageArray = null;
    }

}
